package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.dto.AgentScoreDTO;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.AgentScoreEntity;
import com.fjwt.gz.db.vo.AgentScoreVO;
import com.fjwt.gz.service.mapper.AgentScoreMapper;
import com.fjwt.gz.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 机构积分类别表（同一个地市多套积分共存） 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AgentScoreService extends ServiceImpl<AgentScoreMapper, AgentScoreEntity> {

    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private AgentScoreService agentScoreService;

    /**
     * 分页列表
     *
     * @param iPage
     * @param agentScoreDTO
     * @return
     */
    public IPage<AgentScoreVO> page(IPage iPage, AgentScoreDTO agentScoreDTO) {
        LambdaQueryWrapper<AgentScoreEntity> gw = AgentScoreEntity.gw()
                .eq(AgentScoreEntity::getAgentNo, agentScoreDTO.getAgentNo())
                .eq(AgentScoreEntity::getIsDefault, agentScoreDTO.getIsDefault());
        IPage<AgentScoreEntity> selectedPage = baseMapper.selectPage(iPage, gw);
        IPage<AgentScoreVO> pageVo = selectedPage.convert(entity -> {
            AgentScoreVO vo = BeanUtil.copyProperties(entity, AgentScoreVO.class);
            return vo;
        });
        return pageVo;
    }

    /**
     * 新增
     *
     * @param agentScoreDTO
     */
    public void add(AgentScoreDTO agentScoreDTO) {
        if (ObjectUtils.isEmpty(agentScoreDTO.getAgentNo())) {
            throw new BizException("请选择机构");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getScoreName())) {
            throw new BizException("请输入类别名称");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getScoreRatio())) {
            throw new BizException("请输入兑换比例");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getIsDefault())) {
            throw new BizException("请选择是否默认");
        }
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(agentScoreDTO.getAgentNo());
        if (ObjectUtils.isEmpty(agentInfo)) {
            throw new BizException("所选机构不存在");
        }
        AgentScoreEntity agentScore = baseMapper.selectOne(AgentScoreEntity.gw().eq(AgentScoreEntity::getAgentNo, agentScoreDTO.getAgentNo()).eq(AgentScoreEntity::getIsDefault, agentScoreDTO.getIsDefault()));
        if (ObjectUtils.isNotEmpty(agentScore)) {
            throw new BizException("所选机构下已存在默认类别");
        }

        AgentScoreEntity agentScoreEntity = new AgentScoreEntity();
        BeanUtils.copyProperties(agentScoreDTO, agentScoreEntity);
        agentScoreEntity.setAgentNo1(agentInfo.getAgentNo1());
        agentScoreEntity.setAgentNo2(agentInfo.getAgentNo2());
        agentScoreEntity.setAgentNo3(agentInfo.getAgentNo3());
        agentScoreEntity.setAgentNo4(agentInfo.getAgentNo4());

        baseMapper.insert(agentScoreEntity);
    }

    /**
     * 修改
     *
     * @param agentScoreDTO
     */
    public void update(AgentScoreDTO agentScoreDTO) {
        if (ObjectUtils.isEmpty(agentScoreDTO.getAgentScoreId())) {
            throw new BizException("请选择要修改的数据");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getAgentNo())) {
            throw new BizException("请选择机构");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getScoreName())) {
            throw new BizException("请输入类别名称");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getScoreRatio())) {
            throw new BizException("请输入兑换比例");
        }
        if (ObjectUtils.isEmpty(agentScoreDTO.getIsDefault())) {
            throw new BizException("请选择是否默认");
        }
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(agentScoreDTO.getAgentNo());
        if (ObjectUtils.isEmpty(agentInfo)) {
            throw new BizException("所选机构不存在");
        }

        AgentScoreEntity agentScoreEntity = baseMapper.selectById(agentScoreDTO.getAgentScoreId());
        if (ObjectUtils.isEmpty(agentScoreEntity)) {
            throw new BizException("所选数据异常");
        }

        BeanUtils.copyProperties(agentScoreDTO, agentScoreEntity);
        agentScoreEntity.setAgentNo1(agentInfo.getAgentNo1());
        agentScoreEntity.setAgentNo2(agentInfo.getAgentNo2());
        agentScoreEntity.setAgentNo3(agentInfo.getAgentNo3());
        agentScoreEntity.setAgentNo4(agentInfo.getAgentNo4());

        baseMapper.updateById(agentScoreEntity);
    }

    /**
     * 详情
     *
     * @param agentScoreDTO
     * @return
     */
    public AgentScoreEntity detail(AgentScoreDTO agentScoreDTO) {
        if (ObjectUtils.isEmpty(agentScoreDTO.getAgentScoreId())) {
            throw new BizException("请选择要查看的数据");
        }
        return baseMapper.selectById(agentScoreDTO.getAgentScoreId());
    }


    /**根据机构号查询机构配置的机构类别信息**/
  /*  public AgentScoreEntity getAgentScoreByAgentNo(String agentNo) {
        //通过机构号查询，如果没有向上级机构查询数据，直到查询到数据
        LambdaQueryWrapper<AgentScoreEntity> gw = AgentScoreEntity.gw();
        gw.eq(AgentScoreEntity::getAgentNo, agentNo);
        AgentScoreEntity agentScoreEntity = baseMapper.selectOne(gw);
        if (ObjectUtils.isNotEmpty(agentScoreEntity)){
            return agentScoreEntity;
        }

        //查询上级机构
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(agentNo);
        Integer level = agentInfo.getLevel();
        if (level==4){
            //查询三级
            LambdaQueryWrapper<AgentScoreEntity> gw43 = AgentScoreEntity.gw();
            gw43.eq(AgentScoreEntity::getAgentNo, agentInfo.getAgentNo3());
            agentScoreEntity = baseMapper.selectOne(gw43);
            if (ObjectUtils.isNotEmpty(agentScoreEntity)){
                return agentScoreEntity;
            }
            //查询二级
            LambdaQueryWrapper<AgentScoreEntity> gw42 = AgentScoreEntity.gw();
            gw42.eq(AgentScoreEntity::getAgentNo, agentInfo.getAgentNo2());
            agentScoreEntity = baseMapper.selectOne(gw42);
            if (ObjectUtils.isNotEmpty(agentScoreEntity)){
                return agentScoreEntity;
            }
            //查询一级
            LambdaQueryWrapper<AgentScoreEntity> gw41 = AgentScoreEntity.gw();
            gw41.eq(AgentScoreEntity::getAgentNo, agentInfo.getAgentNo1());
            agentScoreEntity = baseMapper.selectOne(gw41);
            return agentScoreEntity;
        } else if (level == 3) {
            //查询二级
            LambdaQueryWrapper<AgentScoreEntity> gw32 = AgentScoreEntity.gw();
            gw32.eq(AgentScoreEntity::getAgentNo, agentInfo.getAgentNo2());
            agentScoreEntity = baseMapper.selectOne(gw32);
            if (ObjectUtils.isNotEmpty(agentScoreEntity)){
                return agentScoreEntity;
            }
            //查询一级
            LambdaQueryWrapper<AgentScoreEntity> gw31 = AgentScoreEntity.gw();
            gw31.eq(AgentScoreEntity::getAgentNo, agentInfo.getAgentNo1());
            agentScoreEntity = baseMapper.selectOne(gw31);
            return agentScoreEntity;
        } else if (level==2) {
            //查询一级
            LambdaQueryWrapper<AgentScoreEntity> gw21 = AgentScoreEntity.gw();
            gw21.eq(AgentScoreEntity::getAgentNo, agentInfo.getAgentNo1());
             agentScoreEntity = baseMapper.selectOne(gw21);
             return agentScoreEntity;
        } else if (level==1) {
            throw new BizException("该机构未配置积分类别");
        }


        return agentScoreEntity;
    }
*/

    /**
     * 根据机构号递归查询机构配置的机构类别信息
     */
    public AgentScoreEntity getAgentScoreByAgentNo(String agentNo) {

        //从redis中获取积分类别信息
        String agnetScoreKey = String.format("%s:%s:%s", Constants.REDIS_ACTIVITY.AGENTSCORE, Constants.REDIS_ACTIVITY.AGENTNO, agentNo);//用户参会活动次数redis缓存key
        AgentScoreEntity agentScoreEntity = RedisUtil.getObject(agnetScoreKey, AgentScoreEntity.class);
        log.info("从redis中获取积分类别,key：{}，信息是：{}", agnetScoreKey, JsonUtils.toJson(agentScoreEntity));
        if (ObjectUtils.isNotEmpty(agentScoreEntity)) {
            return agentScoreEntity;
        }

        // 当前机构查询
        AgentScoreEntity current = getScoreByAgentNo(agentNo);
        if (ObjectUtils.isNotEmpty(current)) {
            return current;
        }

        // 递归查询上级机构
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(agentNo);
        agentScoreEntity = recursiveFindParentScore(agentInfo, agentInfo.getLevel());
        log.info("向redis中放积分类别信息，key：{}，value:{}", agnetScoreKey, agentScoreEntity);
        RedisUtil.set(agnetScoreKey, agentScoreEntity);
        return agentScoreEntity;
    }

    /**
     * 递归向上查询父级机构
     */
    private AgentScoreEntity recursiveFindParentScore(AgentInfoEntity currentAgent, int currentLevel) {
        if (currentLevel == 1) {
            throw new BizException("该机构未配置积分类别");
        }

        // 获取上级机构号（根据层级动态获取）
        String parentAgentNo = switch (currentLevel) {
            case 4 -> currentAgent.getAgentNo3();
            case 3 -> currentAgent.getAgentNo2();
            case 2 -> currentAgent.getAgentNo1();
            default -> throw new IllegalArgumentException("无效机构层级");
        };

        // 查询上级机构配置
        AgentScoreEntity parentScore = getScoreByAgentNo(parentAgentNo);
        if (ObjectUtils.isNotEmpty(parentScore)) {
            return parentScore;
        }

        // 继续向上递归（层级递减）
        return recursiveFindParentScore(
                agentInfoService.getAgentInfo(parentAgentNo), // 获取上级机构信息
                currentLevel - 1                             // 层级递减
        );
    }

    /**
     * 封装基础查询逻辑
     */
    private AgentScoreEntity getScoreByAgentNo(String agentNo) {
        return baseMapper.selectOne(AgentScoreEntity.gw()
                .eq(AgentScoreEntity::getAgentNo, agentNo)
                .eq(AgentScoreEntity::getIsDefault, 0));
    }

    public AgentScoreEntity addAgentScore(String agentNo,String scoreName,Integer scoreRatio,Integer isDefault) {
        if(StringUtils.isEmpty(agentNo) || StringUtils.isEmpty(scoreName) || Objects.isNull(scoreRatio) || Objects.isNull(isDefault)){
            return null;
        }
        LambdaQueryWrapper<AgentScoreEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentScoreEntity::getAgentNo,agentNo);
        queryWrapper.eq(AgentScoreEntity::getIsDefault,0);
        AgentScoreEntity dto = agentScoreService.getOne(queryWrapper);
        if(Objects.nonNull(dto)){
            return dto;
        }
        AgentInfoEntity agentInfo = agentInfoService.getById(agentNo);
        AgentScoreEntity entity = new AgentScoreEntity();
        entity.setAgentNo(agentNo);
        entity.setCreatedAt(new Date());
        entity.setScoreName(scoreName);
        entity.setScoreRatio(scoreRatio);
        entity.setIsDefault(isDefault);
        entity.setAgentNo1(agentInfo.getAgentNo1());
        entity.setAgentNo2(agentInfo.getAgentNo2());
        entity.setAgentNo3(agentInfo.getAgentNo3());
        entity.setAgentNo4(agentInfo.getAgentNo4());
        int i = agentScoreService.getBaseMapper().insert(entity);
        return i>0?entity:null;
    }
}
